﻿using System;
using System.ComponentModel;
using System.IO;
using System.Text;
using Cav;
using Cav.BaseClases;
using Nefela.CommonTypes;

namespace Nefela.BusinessLogic
{
    public partial class SettingsBL : BusinessLogicBase
    {
        public SettingsBL()
        {
            InitializeComponent();

            if (this.IsDesignMode)
                return;

            ModelPackegeDocs = new PackegeDocsType();

            docsSetting = Path.Combine(DomainContext.AppDataUserStorage, "config.nefela");
        }

        public SettingsBL(IContainer container)
        {
            container.Add(this);

            InitializeComponent();

            if (this.IsDesignMode)
                return;

            ModelPackegeDocs = new PackegeDocsType();

            docsSetting = Path.Combine(DomainContext.AppDataUserStorage, "config.nefela");

        }

        private String docsSetting;

        public PackegeDocsType ModelPackegeDocs { get; private set; }

        public void ExportDocs(String FileName)
        {
            File.WriteAllBytes(FileName, (new UTF8Encoding()).GetBytes(ModelPackegeDocs.XMLSerialize().ToString()).GZipCompress());
        }

        public void ImportDocs(String FileName)
        {
            var x = (new UTF8Encoding()).GetString(File.ReadAllBytes(FileName).GZipDecompress()).XMLDeserialize<PackegeDocsType>();
            if (x == null)
                return;
            ModelPackegeDocs.LoadFromPackege(x);
            Save();
        }

        public void LoadSetting()
        {
            var pd = docsSetting.XMLDeserializeFromFile<PackegeDocsType>();
            if (pd != null)
            {
                ModelPackegeDocs.LoadFromPackege(pd);
                ModelPackegeDocs.OutputDir = pd.OutputDir;
            }

            ModelPackegeDocs.HasChanged = false;
        }

        public void Save()
        {
            ModelPackegeDocs.XMLSerialize(docsSetting);
        }
    }
}
